from PySide2.QtWidgets import QApplication, QMessageBox, QFileDialog, QDateEdit
from PySide2.QtGui import QIcon
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QDate
from datetime import date, timedelta
import requests
import json
import os
import time
from dgut_requests.dgut import dgutUser


def request_save(url, data, filename):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
    }
    res = requests.post(url, data=data, headers=headers)
    if res.status_code == 200:
        if res.json()['message'].get('respCode') == '0000':
            with open(filename, "w", encoding='utf-8') as f:
                save_data = {item['label']: item['value']
                             for item in res.json()['dictInfoList']}
                f.write(json.dumps(save_data, indent=4, ensure_ascii=False))


def update_info():
    '''
    更新申请类型和政治面貌
    '''
    url = 'http://sa.dgut.edu.cn/sahWeb/affairs/hall/nightLate/manage/queryDict.do'
    data_type = {'type': 'goOut_type'}
    data_politicCountenance = {'type': 'clan_type'}
    if not os.path.exists("apply_type.json"):
        request_save(url, data_type, "apply_type.json")
    if not os.path.exists("politic_countenance.json"):
        request_save(url, data_politicCountenance, "politic_countenance.json")
    now = time.time()
    if (now - os.path.getmtime("apply_type.json")) > 86400 * 2 or ((now - os.path.getmtime("politic_countenance.json")) > 86400 * 2):
        request_save(url, data_type, "apply_type.json")
        request_save(url, data_politicCountenance,
                     "politic_countenance.json")


class Apply:
    def __init__(self):
        # 从文件中加载UI定义

        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        self.ui = QUiLoader().load('apply.ui')

        now = date.today()
        self.ui.beginDate.setDate(QDate(now.year, now.month, now.day))
        self.ui.endDate.setDate(QDate(now.year, now.month, now.day))
        self.option_load()
        self.form_load()
        self.ui.submit.clicked.connect(self.apply)
        self.ui.reset.clicked.connect(self.reset)
        # self.ui.uncompress.clicked.connect(self.Uncompress)
        # self.ui.preview_in.clicked.connect(self.Preview_in)
        # self.ui.filenames_in.setPlaceholderText("这里显示文件名")
        # self.ui.preview_out.clicked.connect(self.Preview_out)
        # self.ui.compress_choice.currentIndexChanged.connect(
        #     self.Update_filename)
        # self.ui.filedir_out.setText(self.desktop)

        # self.ui.preview_in_2.clicked.connect(self.Preview_in_2)
        # self.ui.preview_out_2.clicked.connect(self.Preview_out_2)
        # self.ui.filedir_out_2.setText(self.desktop)

    def apply(self):
        beginDate = date(self.ui.beginDate.date().year(
        ), self.ui.beginDate.date().month(), self.ui.beginDate.date().day())
        endDate = date(self.ui.endDate.date().year(
        ), self.ui.endDate.date().month(), self.ui.endDate.date().day())
        if self.ui.username.text() and self.ui.password.text() and self.ui.type.currentText() and self.ui.politicCountenance.currentText() and (endDate-beginDate) >= timedelta(0):
            data = {
                'politicCountenance': self.politic_countenance_data.get(self.ui.politicCountenance.currentText()),
                'type': self.apply_type_data.get(self.ui.type.currentText()),
                'reason': self.ui.reason.toPlainText(),
                'beginDate': beginDate.strftime("%Y-%m-%d"),
                'endDate': endDate.strftime("%Y-%m-%d"),
                'isLoan': 'undefined',
            }
            if self.ui.saveForm.isChecked():
                # 保存账号密码
                with open("user.json", "w", encoding='utf-8') as f:
                    f.write(json.dumps({
                        'username': self.ui.username.text(),
                        'password': self.ui.password.text(),
                    }, indent=4, ensure_ascii=False))
            if self.ui.saveUser.isChecked():
                # 保存表单
                with open("form.json", 'w', encoding='utf-8') as f:
                    f.write(json.dumps({
                        'politicCountenance': self.ui.politicCountenance.currentText(),
                        'type': self.ui.type.currentText(),
                        'reason': data.get('reason')
                    }, indent=4, ensure_ascii=False))
            u = dgutUser(self.ui.username.text(), self.ui.password.text())
            try:
                u.signin(
                    "https://cas.dgut.edu.cn/home/Oauth/getToken/appid/stuaffair/state/home.html")
            except:
                QMessageBox.critical(self.ui, '认证失败', '认证失败，可能是账号/密码错误或服务器拥堵')

            u.session.get(
                "http://sa.dgut.edu.cn/app/views/inner/tabViews/home.html")
            u.session.post(
                "http://sa.dgut.edu.cn/sahWeb/affairs/hall/sms/basicinfo/getbasicInfo.do")
            u.session.post(
                "http://sa.dgut.edu.cn/sahWeb/affairs/hall/goOutApply/person/queryConfig.do")
            response = u.session.post(
                "http://sa.dgut.edu.cn/sahWeb/affairs/hall/goOutApply/person/apply.do", data=data)
            QMessageBox.information(self.ui, '结果', response.json()[
                                    'message'].get('exceptionMsg', 'error'))

    def option_load(self):
        update_info()
        with open("apply_type.json", encoding='utf-8') as f:
            self.apply_type_data = json.loads(f.read())
            [self.ui.type.addItem(i) for i in self.apply_type_data.keys()]
        with open("politic_countenance.json", encoding='utf-8') as f:
            self.politic_countenance_data = json.loads(f.read())
            [self.ui.politicCountenance.addItem(
                i) for i in self.politic_countenance_data.keys()]

    def form_load(self):
        if os.path.exists("user.json"):
            with open("user.json", encoding='utf-8') as f:
                data = json.loads(f.read())
                self.ui.username.setText(data.get('username'))
                self.ui.password.setText(data.get('password'))
        if os.path.exists('form.json'):
            with open("form.json", encoding='utf-8') as f:
                data = json.loads(f.read())
                self.ui.type.setCurrentText(data.get('type'))
                self.ui.politicCountenance.setCurrentText(
                    data.get('politicCountenance'))
                self.ui.reason.setPlainText(data.get('reason'))

    def reset(self):
        self.form_load()


if __name__ == '__main__':
    app = QApplication([])
    app.setWindowIcon(QIcon('dgut.ico'))
    apply = Apply()
    apply.ui.show()
    app.exec_()
